package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            queryUserLikeBlog(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        queryUserLikeBlog(blog);
        return Result.ok(blog);
    }

    private void queryUserLikeBlog(Blog blog){
        // 匿名用户查看时 直接返回
        if (UserHolder.getUser() == null){
            return;
        }
        // 获取预备数据
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null){
            blog.setIsLike(true);
        }
        /*Boolean member = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if (BooleanUtil.isTrue(member)){
            blog.setIsLike(true);
        }*/
    }

    @Override
    public Result likeBlog(Long id) {
        // 1. 获取用户
        Long userId = UserHolder.getUser().getId();
        // 2. 检查用户是否点赞 redis存储LikeBlog
        String key = BLOG_LIKED_KEY + id;
        // Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null){
            // 3.1 没有点赞, 数据库数据点赞数 ++
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            if (update){
                // stringRedisTemplate.opsForSet().add(key,userId.toString());
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            // 3.2 点赞了 移除点赞 数据库点赞数-- 移除redis元素
            boolean update = update().setSql("liked = liked - 1").eq("id",id).update();
            if (update){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        // 1. 查询top5的点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()){
            return Result.ok();
        }
        // 2. 解析用户id
        List<Long> ids = top5.stream().map(Long::valueOf).toList();
        String join = StrUtil.join(",",ids);
        // 3. 查询用户
        // select * from tb_user where id in (?,?) order by field(id,?,?);
        List<UserDTO> userDTOS = userService.query().in("id",ids).last("ORDER BY FIELD(id,"+join+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .toList();
        // 4. 返回
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 2. 保存探店笔记
        blog.setUserId(user.getId());
        boolean save = save(blog);
        if (!save){
            return Result.fail("笔记保存失败！");
        }
        // 3. 查询所有的粉丝
        List<Follow> followUser = followService.query().eq("follow_user_id", user.getId()).list();
        // 4. 推送笔记id
        for (Follow follow : followUser) {
            // 4.1 获取粉丝id
            Long followId = follow.getUserId();
            // 4.2.推送
            String key = FEED_KEY + followId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 3. 返回
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogFollow(Long max, Integer offset) {
        // 1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 匿名访问：返回公开数据（如默认关注列表）或提示“需登录查看个性化内容”
            return Result.ok(Collections.emptyList());
        }
        Long userId = user.getId();
        // 2. 查询收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        // 3. 解析数据：blogId、minTime(最小时间戳)、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        offset = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 3.1 获取id
            ids.add(Long.valueOf(typedTuple.getValue()));
            // 3.2 获取分数
            long time = typedTuple.getScore().longValue();
            // 3.3 获取offset
            if (time == minTime){
                offset++;
            }else {
                minTime = time;
                offset = 1;
            }
        }
        // 4. 根据Id查询blog
        List<Blog> blogs = query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")")
                .list();
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            queryUserLikeBlog(blog);
        }
        // 5. 返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(offset);
        return Result.ok(scrollResult);
    }

    // blog User字段赋值
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
